import os
import socket
import platform
import glob
import re
import json
from tools import *
import urllib
import urllib2

LOG = getlogger(__name__)


def mem_size(line):
    m = re.compile('\D+(\d+)\D+').match(line)
    if m:
        return int(m.group(1)) * 1024
    else:
        return -1


def sys_info():
    ret = {}
    try:
        ret['fqdn'] = socket.getfqdn()
        ret['realse'] = platform.release()
        with open('/proc/meminfo') as f:
            for line in f:
                if line.find('MemTotal') > -1:
                    ret['mem_total'] = mem_size(line)
                elif line.find('SwapTotal') > -1:
                    ret['swap_total'] = mem_size(line)
        with open('/sys/devices/virtual/dmi/id/bios_date') as f:
            ret['bios_date'] = f.read().strip()
        with open('/sys/devices/virtual/dmi/id/product_name') as f:
            ret['product_name'] = f.read().strip()
        with open('/sys/devices/virtual/dmi/id/sys_vendor') as f:
            ret['sys_vendor'] = f.read().strip()
        with open('/proc/version') as f:
            ret['version'] = f.read().strip()
        cpu_phy_count = 0
        cpu_core_count = 0
        model = set()
        with open('/proc/cpuinfo') as f:
            for line in f:
                if line.find('physical id') > -1:
                    print cpu_phy_count
                    cpu_phy_count += 1
                elif line.find('processor') > -1:
                    cpu_core_count += 1
                elif line.find('name') > -1:
                    m = line.replace('model name	:', '')
                    model.add(m.strip())
        ret['cpu_core_count'] = cpu_core_count
        ret['cpu_phy_count'] = cpu_phy_count
        ret['cpu_model'] = str(''.join(model)).replace(' ', '')
    except Exception, ex:
        LOG.error(ex)
    return ret


def size(device):
    nr_sectors = open(device + '/size').read().rstrip('\n')
    sect_size = open(device + '/queue/hw_sector_size').read().rstrip('\n')
    return int(nr_sectors) * float(sect_size)


def device_info():
    ret = {}
    dev_pattern = ['sd.*', 'mmcblk*']
    try:
        for device in glob.glob('/sys/block/*'):
            for pattern in dev_pattern:
                if re.compile(pattern).match(os.path.basename(device)):
                    ret[device] = size(device)
    except Exception, ex:
        LOG.error(ex)
    return ret


def disk_usage(path):
    st = os.statvfs(path)
    return st.f_blocks * st.f_frsize


def disk_info():
    phydevs = []
    with open("/proc/filesystems", "r") as f:
        for line in f:
            if not line.startswith("nodev"):
                phydevs.append(line.strip())
    ret = {}
    with open('/etc/mtab', "r") as f:
        for line in f:
            try:
                fields = line.split()
                device = fields[0]
                mountpoint = fields[1]
                fstype = fields[2]
                if fstype not in phydevs:
                    continue
                if device == 'none':
                    device = ''
                ret[mountpoint] = disk_usage(mountpoint)
            except Exception, ex:
                LOG.error(ex)
    return ret


tail = 'info/hardware'


def main():
    a = sys_info()
    b = disk_info()
    c = device_info()
    d = dict(a, **b)
    info = json.dumps(dict(c, **d))
    addr = os.path.join(BASEURL, tail)
    param = urllib.urlencode(dict({'info': info}))
    f = urllib2.urlopen(addr, param)
    code = f.getcode()
    result = f.read()
    if code == 200:
        return result
    else:
        raise Exception('HTTP COEE:%d' % code)
